package com.lokyiu.mybible.db.sqlite;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lokyiu.mybible.dao.ChapterDao;
import com.lokyiu.mybible.db.sqlite.def.BookColumns;
import com.lokyiu.mybible.db.sqlite.def.ChapterColumns;
import com.lokyiu.mybible.domain.BibleBook;
import com.lokyiu.mybible.domain.Chapter;

public class ChapterDaoImpl implements ChapterDao {
	
	private SQLiteDatabase db;
	
	public ChapterDaoImpl(SQLiteDatabase db){
		this.db = db;
	}
	
	public List<Chapter> getChapters(){
		List<Chapter> chapters = new ArrayList<Chapter>();
		Cursor cursor = db.query(ChapterColumns.TABLENAME, new String[] {ChapterColumns.CHAPTER_BIBLEBOOK,ChapterColumns.CHAPTERS_NUMBER,},
				null, null, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				Chapter chapter = new Chapter(cursor.getString(0),Integer.parseInt(cursor.getString(1)),"");
				chapters.add(chapter);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return chapters;
	}
	
	public void saveChapter(Chapter chapter){
		ContentValues values = new ContentValues();
		values.put(ChapterColumns.CHAPTER_BIBLEBOOK, chapter.getBibleBook());
		values.put(ChapterColumns.CHAPTERS_NUMBER, chapter.getChapterNumber());
		db.insert(ChapterColumns.TABLENAME, null, values);
	}
	
	public void saveChapters(List<Chapter> chapters){
		db.beginTransaction();
		for(Chapter chapter: chapters){
			saveChapter(chapter);
		}
		db.setTransactionSuccessful();
		db.endTransaction();
	}

	@Override
	public List<Chapter> getChapters(String bookName) {
		List<Chapter> chapters = new ArrayList<Chapter>();
		Cursor cursor = db.query(ChapterColumns.TABLENAME, new String[] {ChapterColumns.CHAPTER_BIBLEBOOK,ChapterColumns.CHAPTERS_NUMBER},
				ChapterColumns.CHAPTER_BIBLEBOOK + "=?",
				new String[] {bookName}, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				Chapter chapter = new Chapter(cursor.getString(0),Integer.parseInt(cursor.getString(1)),"");
				chapters.add(chapter);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return chapters;
	}
}
